package com.lipuwater.agent.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ismartlib.anim.CircularAnim;
import com.ismartlib.ui.widget.SlidingLinearLayout;
import com.ismartlib.utils.ActivityList;
import com.ismartlib.utils.DisplayUtil;
import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.bean.user.UserInfoBean;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;
import mehdi.sakout.fancybuttons.FancyButton;
import okhttp3.Call;


public class LoginActivity extends BaseLayoutActivity {

    @Bind(R.id.mProgressbar)
    ProgressBar mProgressbar;
    @Bind(R.id.layout_login)
    RelativeLayout layoutLogin;
    @Bind(R.id.edit_phone)
    EditText editPhone;
    @Bind(R.id.edit_vcode)
    EditText editVcode;
    @Bind(R.id.btn_login)
    FancyButton btnLogin;
    @Bind(R.id.layout_sliding)
    SlidingLinearLayout layoutSliding;
    @Bind(R.id.layout_root)
    RelativeLayout layoutRoot;
    @Bind(R.id.checkBox)
    CheckBox checkBox;
    @Bind(R.id.text_agreement)
    TextView textAgreement;
    private int slidingHeight;
    private int slidingState = 0;
    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_login);
        startActivity();
        ButterKnife.bind(this);
        initTitle();
        //滚动高度
        slidingHeight = DisplayUtil.dip2px(LoginActivity.this, 110);
        //监听软键盘
        layoutRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                int heightDifference = screenHeight - r.bottom;
                if (heightDifference > 0 && slidingState != 1) {
                    slidingState = 1;
                    layoutSliding.ScrollToY(0, slidingHeight);
                } else if (heightDifference == 0 && slidingState != 0) {
                    slidingState = 0;
                    layoutSliding.ScrollToY(layoutSliding.getCurrY(), -slidingHeight);
                }
            }
        });
    }

    private void startActivity() {
        if (isLogin) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            ActivityList.getInstance().exit();
        }
    }

    private void initTitle() {
        initTitle(0, "登录");
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
        layout_left.setEnabled(false);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    textAgreement.setTextColor(ContextCompat.getColor(LoginActivity.this, R.color.themeColor));
                } else {
                    textAgreement.setTextColor(0xffb3b3b3);
                }
            }
        });
    }

    @OnClick({R.id.btn_login, R.id.text_agreement,R.id.text_find_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if (!checkBox.isChecked()) {
                    Toast("请阅读并同意用户使用协议");
                    return;
                }
                if (editPhone.getText().toString().equals("")) {
                    Toast("请输入账号");
                } else if (editVcode.getText().toString().equals("")) {
                    Toast("请输入密码");
                } else {
                    setEnabled(false);
                    login();
                }
                break;
            case R.id.text_agreement:
                if (mNoDoubleClick.check()) return;
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "使用协议");
                intent.putExtra("url", HttpConfig.TOS);
                startActivity(intent);
                break;
            case R.id.text_find_password:
                startActivity(new Intent(this,FindPasswordActivity.class));
                break;
        }
    }

    private void login() {
        Map<String, Object> params = new HashMap<>();
        params.put("loginName", editPhone.getText().toString());
        params.put("password", editVcode.getText().toString());
        setEnabled(false);
        ApiRequestsBasis.Login(this, params, new ApiCallBack() {
            @Override
            public void onResponse(final ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    CircularAnim.fullActivity(LoginActivity.this, btnLogin).go(new CircularAnim.OnAnimationEndListener() {
                        @Override
                        public void onAnimationEnd() {
                            saveUserInfo(result);
                            Toast("登录成功");
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            ActivityList.getInstance().exit();
                        }
                    });
                } else {
                    Toast(result.getMessage());
                    setEnabled(true);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (NetUtils.isConnected(LoginActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
                setEnabled(true);
            }
        });
    }

    private void setEnabled(boolean enabled) {
        editPhone.setEnabled(enabled);
        editVcode.setEnabled(enabled);
        if (enabled) {
            mProgressbar.setVisibility(View.GONE);
            CircularAnim.show(btnLogin).go();
        } else {
            mProgressbar.setVisibility(View.VISIBLE);
            CircularAnim.hide(btnLogin).go();
        }
    }

    private void saveUserInfo(ResponseParams result) {
        Map<String, Object> params = (Map<String, Object>) result.getParams().get("userInfo");
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        UserInfoBean userInfoBean = realm.createObject(UserInfoBean.class);
        userInfoBean.setId((String) params.get("id"));
        userInfoBean.setLogin(true);
        userInfoBean.setName((String) params.get("name"));
        userInfoBean.setAccount((String) params.get("loginName"));
        userInfoBean.setToken((String) params.get("token"));
        userInfoBean.setOrginPath((String) params.get("orginPath"));
        userInfoBean.setThumbPath((String) params.get("thumbPath"));
        List<Map<String, Object>> roleList = (List<Map<String, Object>>) params.get("roleList");
        if (roleList != null && roleList.size() > 0 && roleList.get(0) != null) {
            userInfoBean.setRoleName((String) roleList.get(0).get("name"));
            userInfoBean.setEnname((String) roleList.get(0).get("enname"));
        }
        realm.commitTransaction();
        realm.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


}
